// work/pages/shareDoc/shareDoc.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    docList: [],
    userList: []
  },

  // 获取共享文档
  getDoc() {
    var url = app.globalData.url + 'shareDoc/listDoc',
      that = this,
      docList = [],
      userList = this.data.userList;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
      userId: app.globalData.memberId,
      department: app.globalData.departmentId,
      flag: 1
    }, res => {
      if (res.flag) {
        console.log(res);
        docList = res.data
        docList.forEach(item => {
          item.memberName = ''
          userList.forEach(ele => {
            if (item.docAuth == ele.member_id) {
              item.memberName = ele.member_name
            }
          })
        })
        console.log(docList);
        that.setData({
          docList
        })
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })

  },
  getMembersList() {
    wx.showLoading({
      title: '',
    })
    var url = app.globalData.url + "member/getMembersList",
      that = this,
      userList = [];
    app.wxRequest(url, {
      status: 0,
      name: '',
      flag: 1,
    }, res => {
      console.log(res);
      if (res.flag) {
        wx.hideLoading()
        var datas = res.data
        userList = datas.memberList;

        that.setData({
          userList
        })
        this.getDoc()
      }
    })
  },

  // 查看
  toDetail(e) {
    var index = e.currentTarget.dataset.index,
      docList = this.data.docList,
      that = this,
      url = docList[index].docContent;
    // 已经打开过
    if (docList[index].path != undefined) {
      wx.openDocument({
        filePath: docList[index].path,
        fileType: 'pdf',
        showMenu: true,
        success: function (res) {
          console.log('打开文档成功');
        }
      })
      return
    }
    // 未打开
    wx.showLoading({
      title: '加载中...',
    })
    wx.downloadFile({
      filePath: '', //指定文件下载后存储的路径
      url: url, //下载资源的 url
      success: (res) => {
        console.log(res);
        wx.hideLoading()
        docList[index].path = res.tempFilePath
        that.setData({
          docList
        })
        wx.openDocument({
          filePath: res.tempFilePath,
          fileType: 'pdf',
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功');
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getMembersList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getDoc()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})